#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("TCP - 服务端");

    ui->send_pushButton->setDisabled(true);

    ui->port_text->setText("8899");
    tcpServer = new QTcpServer(this);

    connect(tcpServer, &QTcpServer::newConnection, this, [=](){
        socket = tcpServer->nextPendingConnection();

        lable->setPixmap(QPixmap(":/image/dui.png").scaled(40, 40));
        ui->send_pushButton->setDisabled(false);

        connect(socket, &QTcpSocket::readyRead, this, [=](){
            QByteArray data = socket->readAll();
            ui->log_textEdit->append("客户端：" + data);
        });

        connect(socket, &QTcpSocket::disconnected, this, [=](){
            socket->close();
            socket->deleteLater();
            lable->setPixmap(QPixmap(":/image/cuo.png").scaled(40, 40));
            ui->send_pushButton->setDisabled(true);
        });
    });

    lable = new QLabel;
    lable->setPixmap(QPixmap(":/image/cuo.png").scaled(40, 40));
    ui->statusbar->addWidget(new QLabel("连接状态："));
    ui->statusbar->addWidget(lable);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_start_pushButton_clicked()
{
    unsigned short port = ui->port_text->text().toUShort();
    tcpServer->listen(QHostAddress::Any, port);
    ui->start_pushButton->setDisabled(true);
    ui->log_textEdit->append("服务器开始监听数据...");
}


void MainWindow::on_send_pushButton_clicked()
{
    QString msg = ui->msg_textEdit->toPlainText();
    socket->write(msg.toUtf8());
    ui->log_textEdit->append("服务器：" + msg);
}

